package org.minbox.chapter.seata.service;

import com.cloud.model.account.Account;
import org.minbox.chapter.seata.mapper.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

/**
 * 账户业务逻辑处理
 *
 * @author 恒宇少年
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class AccountService {

    @Autowired
    private AccountMapper accountMapper;


    public boolean deduction(Integer accountId, Double money) {
        Account account = accountMapper.selectOne(accountId);
        if (ObjectUtils.isEmpty(account)) {
            throw new RuntimeException("账户：" + accountId + "，不存在.");
        }
        if (account.getMoney() - money < 0) {
            throw new RuntimeException("账户：" + accountId + "，余额不足.");
        }
        account.setMoney(money);
        boolean update = accountMapper.update(account);

        return  update;
    }
}
